using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Threading;

namespace Spike.ContractBuilder
{
    public class ServiceLoggingConfiguration : ConfigurationSection
    {
        internal const string SectionName = "Spike.ContractBuilder.ServiceTraceListener";

        static ServiceLoggingConfiguration configuration = null;
        static object _configurationLock = new object();
        static int _recursionGuard = 0;

        [ConfigurationProperty("maxFileSizeBytes", IsKey = true, IsRequired = true)]
        public int MaxFileSizeBytes
        {
            get { return (int)this["maxFileSizeBytes"]; }
        }

        [ConfigurationProperty("maxDurationMinutes", IsKey = true, IsRequired = true)]
        public int MaxDurationMinutes
        {
            get { return (int)this["maxDurationMinutes"]; }
        }

        #region Current static method
        static public ServiceLoggingConfiguration Current
        {
            get
            {
                if (ServiceLoggingConfiguration.configuration == null)
                {
                    lock (_configurationLock)
                    {
                        if (ServiceLoggingConfiguration.configuration == null)
                        {
                            ServiceLoggingConfiguration configuration = null;
                            if (Interlocked.CompareExchange(ref _recursionGuard, 1, 0) > 0)
                            {
                                throw new ConfigurationErrorsException("LoggingConfigurationNotInitialized");
                            }
                            try
                            {
                                if (configuration == null)
                                {
                                    configuration = (ServiceLoggingConfiguration)ConfigurationManager.GetSection(ServiceLoggingConfiguration.SectionName);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new ConfigurationErrorsException(ex.Message);
                            }
                            if (configuration == null)
                            {
                                configuration = new ServiceLoggingConfiguration();
                            }
                            ServiceLoggingConfiguration.configuration = configuration;
                        }
                    }
                }
                return ServiceLoggingConfiguration.configuration;
            }
        }
        #endregion
    }
}
